import { login, logout, getInfo } from '@/api/user';

const state = {
	sessionKey: '',
	userInfo: {},
};
const mutations = {
	SESSION_KEY: (state, sessionKey) => {
		state.sessionKey = sessionKey;
	},
	USER_INFO: (state, userInfo) => {
		state.userInfo = userInfo;
	},
};
const actions = {
	// 登录
	login({ commit }, postData) {
		// const { username, password } = userInfo;
		return new Promise((resolve, reject) => {
			login(postData)
				.then((response) => {
					const { data } = response;
					commit('SESSION_KEY', data.sessionKey);
					uni.setStorageSync('sessionKey', data.sessionKey);
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	},
	// 获取用户信息
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getInfo(state.sessionKey)
				.then((response) => {
					const { data } = response;
					commit('USER_INFO', data.userInfo);
					uni.setStorageSync('USER_INFO', JSON.stringify(data.userInfo));
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	},
	// 退出
	logout({ commit }) {
		return new Promise((resolve, reject) => {
			logout()
				.then((response) => {
					commit('SESSION_KEY', '');
					commit('USER_INFO', {});
					uni.removeStorageSync('sessionKey');
					uni.removeStorageSync('userInfo');
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	},
};
export default {
	namespaced: true,
	state,
	mutations,
	actions,
};
